﻿using System;
using System.CodeDom;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Threading;

namespace OfficeMiddlewareService
{
    public partial class Service1 : ServiceBase
    {
        private Thread _thread;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {


            _thread = new Thread(() =>
           {
               var file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "正文运行环境.exe");

               while (true)
               {
                   try
                   {
                       if (!CheckProcess())
                       {
                           var processService = new ProcessServices();
                           processService.StartProcessAsCurrentUser(file);
                       }
                   }
                   catch (System.Exception)
                   {
                       throw;
                   }


                   Thread.Sleep(5000);
               }
           });
            _thread.Start();

            bool CheckProcess()
            {
                var ps = Process.GetProcessesByName("正文运行环境");
                var hasProcess = false;
                foreach (var item in ps)
                {
                    if (item.HasExited) continue;
                    if (hasProcess)
                    {
                        item.Kill();
                    }
                    else
                    {
                        hasProcess = true;
                    }
                }
                return hasProcess;
            }
        }

        protected override void OnStop()
        {
            _thread.Abort();
            _thread = null;
        }
    }
}
